import React, { useState, useEffect } from 'react';
import { Space, Table, Button, Modal, Form, Input, message, Pagination } from 'antd';

import { getBannerList, deleteBanner, addBanner } from '../../api/banner';

const BannerAdd = () => {
  const [data, setData] = useState([]);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    fetchData();
  }, );

  const handleDelete = (id) => {
    deleteBanner({ id })
      .then(() => {
        message.success(`删除轮播图${id}成功`);
        fetchData();
      })
      .catch((error) => {
        console.error('删除轮播图失败:', error);
      });
  };

  const handleAdd = () => {
    form.validateFields()
      .then((values) => {
        addBanner(values)
          .then(() => {
            message.success('添加轮播图成功');
            fetchData();
            form.resetFields();
            setOpen(false);
          })
          .catch((error) => {
            console.error('添加轮播图失败:', error);
          });
      })
      .catch((error) => {
        console.error('表单验证失败:', error);
      });
  };

  const fetchData = () => {
    getBannerList(current)
      .then((response) => {
        const { data } = response;

        if (Array.isArray(data.data)) {
          const filteredData = data.data.filter((item) => item.banner_src !== 'undefined' && item.banner_des !== 'undefined');
          setData(filteredData);
          setTotal(data.total);
        } else {
          console.error('获取到的轮播图列表数据不是一个数组:', data);
        }
      })
      .catch((error) => {
        console.error('获取轮播图列表失败:', error);
      });
  };

  const handleModalCancel = () => {
    form.resetFields();
    setOpen(false);
  };

  const handlePageChange = (page) => {
    setCurrent(page);
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'banner_id',
      key: 'banner_id',
    },
    {
      title: '图片',
      key: 'banner_src',
      render: (_, record) => <img src={record.banner_src} alt="Banner" style={{ width: '100px' }} />,
    },
    {
      title: '描述',
      dataIndex: 'banner_des',
      key: 'banner_des',
    },
    {
      title: '删除',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => handleDelete(record.banner_id)}>删除</Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <Button type="primary" onClick={() => setOpen(true)}>添加轮播图</Button>
      <Table
        columns={columns}
        dataSource={data.map((item) => ({ ...item, key: item.banner_id }))}
        pagination={false}
      />
      <Pagination
        current={current}
        total={total}
        onChange={handlePageChange}
        showSizeChanger={false}
      />
      <Modal
        title="添加轮播图"
        open={open} // 使用 open 属性
        onCancel={handleModalCancel}
        onOk={handleAdd}
      >
        <Form form={form}>
          <Form.Item
            name="banner_src"
            label="图片链接"
            rules={[{ required: true, message: '请输入图片链接' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="banner_des"
            label="描述"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default BannerAdd;







